import Vue from 'vue'
import wx from 'weixin-js-sdk'
import http from './http'
import inbound from './Inbound'

const wechat = {
  //静默授权
  login () {
    var redirect = 'https://open.weixin.qq.com/connect/oauth2/authorize'
    redirect += '?appid=' + process.env.appId
    redirect += '&redirect_uri=' + encodeURIComponent(window.location.href)
    redirect += '&response_type=code'
    redirect += '&scope=snsapi_userinfo'
    redirect += '#wechat_redirect'
    window.location.href = redirect
  },
  //初始化微信
  config () {
    return new Promise((resolve, reject) => {
      //向服务端请求 公众号权限参数
      http.post('/wechat/appid/getWeChatMpConfig.do', {
        appId: process.env.appId,
        url: window.location.href
      }).then(v => {
        let config = v.data

        //注入参数
        wx.config({
          debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: config.appId, // 必填，公众号的唯一标识
          timestamp: config.timestamp, // 必填，生成签名的时间戳
          nonceStr: config.nonceStr, // 必填，生成签名的随机串
          signature: config.signature,// 必填，签名
          jsApiList: [] // 必填，需要使用的JS接口列表
        })
      })

      wx.ready(function () {
        resolve()
      })

      //初始化权限失败
      wx.error(function (res) {
        reject(res)
      })
    })
  },
  register (code) {
    return new Promise((resolve, reject) => {
      inbound.invoke({
        interfaceId: 'app.member.register',
        data: {
          appId: process.env.appId,
          code: code
        }
      }).then(v => {
        resolve(v)
      }).catch(e => {
        reject(e)
      })
    })
  }
}

export default {
  ...wechat, ...{
    install: function () {
      Vue.prototype.$wx = wechat
    }
  }
}
